package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysNoticeAttachment;
import com.ruoyi.system.service.ISysNoticeAttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.framework.config.ServerConfig;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 通知附件控制器
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/noticeAttach")
public class SysNoticeAttachmentController extends BaseController {
    @Autowired
    private ISysNoticeAttachmentService noticeAttachmentService;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询通知附件列表
     */
    @PreAuthorize("@ss.hasPermi('system:notice:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysNoticeAttachment noticeAttachment) {
        startPage();
        List<SysNoticeAttachment> list = noticeAttachmentService.selectNoticeAttachmentList(noticeAttachment);
        return getDataTable(list);
    }

    /**
     * 导出通知附件列表
     */
    @PreAuthorize("@ss.hasPermi('system:notice:export')")
    @Log(title = "通知附件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysNoticeAttachment noticeAttachment) {
        List<SysNoticeAttachment> list = noticeAttachmentService.selectNoticeAttachmentList(noticeAttachment);
        ExcelUtil<SysNoticeAttachment> util = new ExcelUtil<SysNoticeAttachment>(SysNoticeAttachment.class);
        util.exportExcel(response, list, "通知附件数据");
    }

    /**
     * 获取通知附件详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:notice:query')")
    @GetMapping(value = "/{attachmentId}")
    public AjaxResult getInfo(@PathVariable("attachmentId") Long attachmentId) {
        return AjaxResult.success(noticeAttachmentService.selectNoticeAttachmentById(attachmentId));
    }

    /**
     * 根据通知ID获取附件列表
     */
    @GetMapping(value = "/byNotice/{noticeId}")
    public AjaxResult getByNoticeId(@PathVariable("noticeId") Long noticeId) {
        return AjaxResult.success(noticeAttachmentService.selectNoticeAttachmentByNoticeId(noticeId));
    }

    /**
     * 新增通知附件
     */
    @PreAuthorize("@ss.hasPermi('system:notice:add')")
    @Log(title = "通知附件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysNoticeAttachment noticeAttachment) {
        return toAjax(noticeAttachmentService.insertNoticeAttachment(noticeAttachment));
    }

    /**
     * 上传通知附件
     */
    @PreAuthorize("@ss.hasPermi('system:notice:add')")
    @Log(title = "通知附件", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file, @RequestParam("noticeId") Long noticeId) {
        try {
            // 校验文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件不能为空");
            }

            // 这里如果我上传的是多个文件，也会反复调用这个接口，不知道为什么运行良好，那就不改造了。

            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;

            // 构建附件信息
            SysNoticeAttachment attachment = new SysNoticeAttachment();
            attachment.setNoticeId(noticeId);
            attachment.setFileName(file.getOriginalFilename());
            attachment.setFilePath(url);
            attachment.setFileSize(file.getSize());
            attachment.setFileType(file.getContentType());

            // 保存附件信息到数据库
            noticeAttachmentService.insertNoticeAttachment(attachment);

            return AjaxResult.success(attachment);
        } catch (Exception e) {
            // 捕获FileUploadUtils抛出的异常（如文件类型不符、大小超限等）
            String message = "上传失败: " + e.getMessage();
            if (StringUtils.isEmpty(e.getMessage())) {
                message = "上传失败，请检查文件是否符合要求";
            }
            return AjaxResult.error(message);
        }
    }


    /**
     * 修改通知附件
     */
    @PreAuthorize("@ss.hasPermi('system:notice:edit')")
    @Log(title = "通知附件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysNoticeAttachment noticeAttachment) {
        return toAjax(noticeAttachmentService.updateNoticeAttachment(noticeAttachment));
    }

    /**
     * 删除通知附件
     */
    @PreAuthorize("@ss.hasPermi('system:notice:remove')")
    @Log(title = "通知附件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{attachmentId}")
    public AjaxResult remove(@PathVariable Long attachmentId) {
        return toAjax(noticeAttachmentService.deleteNoticeAttachmentById(attachmentId));
    }

    /**
     * 下载通知附件
     */
//    @GetMapping("/download/{attachmentId}")
//    public void download(@PathVariable("attachmentId") Long attachmentId, HttpServletResponse response) {
//        try {
//            noticeAttachmentService.downloadAttachment(attachmentId, response);
//        } catch (Exception e) {
//            // 可以添加日志记录
//        }
//    }
}
    